# -*- coding: utf-8 -*-
import scrapy
from datetime import datetime
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from zc_core.model.items import Box
from plap_deli.rules import *
from plap_deli.utils.login import SeleniumLogin
from plap_deli.utils.done_filter import SpuPageLogFilter, MaterialHelper
from zc_core.spiders.base import BaseSpider


class DeliListSpider(BaseSpider):
    name = 'deli_list'
    custom_settings = {
        'CONCURRENT_REQUESTS': 12,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 12,
        'CONCURRENT_REQUESTS_PER_IP': 12,
    }
    # 常用链接
    sku_list_url = 'http://mall.plap.cn/oc/0_0_0_0_0_11278_0_{}_0.html'
    commodity_url = 'http://mall.plap.cn/commodities/{}'

    def __init__(self, batchNo=None, delta_hour=-12, *args, **kwargs):
        super(DeliListSpider, self).__init__(batchNo=batchNo, hourOffset=delta_hour, *args, **kwargs)
        # 避免重复采集
        self.done_filter = SpuPageLogFilter(self.batch_no)
        # 物料编码补全
        self.material_helper = MaterialHelper()

    def start_requests(self):
        cookies = SeleniumLogin().get_cookies('data')
        # cookies = {'_session_id': '305d2d2b2d40c263bfd42bf7d60db5e1'}
        if not cookies:
            self.logger.error('init cookie failed...')
            return
        self.logger.info('init cookie: %s', cookies)

        yield Request(
            url=self.sku_list_url.format(1),
            meta={
                'reqType': 'sku',
                'batchNo': self.batch_no,
            },
            callback=self.parse_total_page,
            errback=self.error_back,
            cookies=cookies,
            priority=200,
            dont_filter=True
        )

    # 处理spu列表
    def parse_total_page(self, response):
        total_page = parse_sku_page(response)
        if total_page > 0:
            self.logger.info('总页数: total=%s' % total_page)
            for page in range(1, total_page + 1):
                yield Request(
                    url=self.sku_list_url.format(page),
                    callback=self.parse_spu,
                    errback=self.error_back,
                    meta={
                        'reqType': 'sku',
                        'batchNo': self.batch_no,
                        'page': page,
                    },
                    priority=100,
                    dont_filter=True
                )

    # 处理spu列表
    def parse_spu(self, response):
        meta = response.meta
        page = meta.get('page')
        sku_list = parse_sku(response)
        if sku_list:
            self.logger.info('清单: page=%s, cnt=%s' % (page, len(sku_list)))
            yield Box('sku', self.batch_no, sku_list)
        else:
            self.logger.info('空页: page=%s' % page)

    # 错误处理

